package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import com.nimbusds.oauth2.sdk.util.MapUtils;
import com.ruoyi.system.domain.dto.WxUnifiedOrderResponse;
import com.ruoyi.system.domain.vo.WxUnifiedOrderRequest;
import com.ruoyi.system.wx.login.WxPaySignUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WxPayServiceImpl
 * @Description
 * @Author sizegang
 * @Date2025/4/22 22:20
 **/
@Service
@RequiredArgsConstructor
public class WxPayService {

    @Value("${wechat.pay.appid}")
    private String appid;

    @Value("${wechat.pay.mch-id}")
    private String mchId;

    @Value("${wechat.pay.key}")
    private String key;

    @Value("${wechat.pay.notify-url}")
    private String notifyUrl;

    @Value("${wechat.pay.unified-order-url}")
    private String unifiedOrderUrl;

//    @Autowired
//    private RestTemplate restTemplate;

    public Map<String, String> createOrder(String openid, String orderNo,
                                           String body, int totalFee, String clientIp)
            throws Exception {

        // 构造统一下单请求参数
        WxUnifiedOrderRequest request = new WxUnifiedOrderRequest();
        request.setAppid(appid);
        request.setMch_id(mchId);
        request.setNonce_str(WxPaySignUtil.generateNonceStr());
        request.setBody(body);
        request.setOut_trade_no(orderNo);
        request.setTotal_fee(totalFee);
        request.setSpbill_create_ip(clientIp);
        request.setNotify_url(notifyUrl);
        request.setTrade_type("JSAPI");
        request.setOpenid(openid);

        // 生成签名
        Map<String, String> params = null;
        String sign = WxPaySignUtil.generateSignature(params, key);
        request.setSign(sign);

        // 发送请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<WxUnifiedOrderRequest> entity = new HttpEntity<>(request, headers);

//        WxUnifiedOrderResponse response = restTemplate.postForObject(
//                unifiedOrderUrl, entity, WxUnifiedOrderResponse.class);
//
//        // 处理响应
//        if (!"SUCCESS".equals(response.getReturn_code())) {
//            throw new RuntimeException("微信下单失败：" + response.getReturn_msg());
//        }
//        if (!"SUCCESS".equals(response.getResult_code())) {
//            throw new RuntimeException("微信下单失败：" + response.getErr_code_des());
//        }

//        // 生成前端支付参数
//        return createPayParams(response.getPrepay_id());
        return null;
    }

    private Map<String, String> createPayParams(String prepayId) {
        Map<String, String> params = new HashMap<>();
        params.put("appId", appid);
        params.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("nonceStr", WxPaySignUtil.generateNonceStr());
        params.put("package", "prepay_id=" + prepayId);
        params.put("signType", "MD5");

        String sign = WxPaySignUtil.generateSignature(params, key);
        params.put("paySign", sign);
        return params;
    }
}